package com.monkey.retrofitdownload;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hly.easyretrofit.download.DownLoadBackListener;
import com.hly.easyretrofit.download.db.DownLoadEntity;
import com.hly.easyretrofit.download.DownLoadManager;
import com.hly.easyretrofit.retrofit.NetWorkRequest;
import com.hly.easyretrofit.retrofit.NetworkResponse;
import com.monkey.retrofitdownload.entity.ResponseLoginEntity;
import com.monkey.retrofitdownload.net.ApiManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView mTvDown;
    private String TAG ="MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mTvDown = (TextView) findViewById(R.id.tv_down);
        ManifestPermission();


        findViewById(R.id.bt_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final List<DownLoadEntity> list = new ArrayList<>();
                DownLoadEntity downLoadModel = new DownLoadEntity();
                downLoadModel.url = "http://shouji.360tpcdn.com/170821/9a7f5c1ee54e3c5bc84070c21e9b5b49/com.tencent.mm_1100.apk";
                downLoadModel.saveName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "aaa.apk";
                list.add(downLoadModel);

                DownLoadManager.getInstance().downLoad(list, "MainActivity", new DownLoadBackListener() {

                    @Override
                    public void onError(DownLoadEntity downLoadEntity, Throwable throwable) {
                        Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onStart(double percent) {
                        mTvDown.setText(String.valueOf(percent * 100));
                        Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "取消了", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onDownLoading(double percent) {
                        mTvDown.setText(String.valueOf(percent * 100));
                    }

                    @Override
                    public void onCompleted() {
                        Toast.makeText(MainActivity.this, "下完了", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        findViewById(R.id.bt_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownLoadManager.getInstance().cancel("MainActivity");
            }
        });


        /**
         *
         * 异步请求
         *
         */

//        NetWorkRequest.getInstance().asyncNetWork(this.getClass().getSimpleName(),
//                1, ApiManager.getInstance().getApiService().login(), new NetworkResponse<ResponseLoginEntity>() {
//            @Override
//            public void onDataReady(ResponseLoginEntity response) {
//
//            }
//
//            @Override
//            public void onDataError(int requestCode, int responseCode, String message) {
//
//            }
//        });
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    //需要校验的权限 读写 文件夹的
    private String[] mPermission = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };
    private List<String> mRequestPermission = new ArrayList<>();
    public static int PERMISSION_REQ = 2;

    //权限校验核心代码
    private void ManifestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String one : mPermission) {
                if (PackageManager.PERMISSION_GRANTED != this.checkPermission(one, Process.myPid(), Process.myUid())) {
                    mRequestPermission.add(one);
                }
            }
            if (!mRequestPermission.isEmpty()) {
                this.requestPermissions(mRequestPermission.toArray(new String[mRequestPermission.size()]), PERMISSION_REQ);
                return;
            }
        }
        startActiviy();
    }

    //权限检验的提示框
    public void startActiviy() {
        if (mRequestPermission.isEmpty()) {
            final ProgressDialog mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setTitle("权限管理");
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.cancel();
                            Log.i(TAG, "startActivity: ");
                        }
                    });
                }
            }).start();
        } else {
            Toast.makeText(this, "请打开您的权限",Toast.LENGTH_LONG).show();
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
